package stack;

import java.util.Arrays;
import java.util.EmptyStackException;

public class MyArrayStack implements MyStack<Object> {

    private Object[] array;

    /**
     * 栈顶指针
     */
    private int top;

    private int size;

    /**
     * 数组无法做到动态伸缩，所以一开始要确定大小
     */
    public MyArrayStack(int size) {
        this.size = size;
        array = new Object[size];
        top = -1;
    }

    @Override
    public void push(Object e) {
        if (top >= size) {
            throw new StackOverflowError();
        }
        if (top == -1) {
            top = 0;
        }
        array[top++] = e;
    }

    @Override
    public Object pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return array[--top];
    }

    @Override
    public Object peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return array[top - 1];
    }

    @Override
    public boolean isEmpty() {
        return top == -1;
    }

    @Override
    public String toString() {
        return "MyArrayStack{" +
                "array=" + Arrays.toString(array) +
                ", top=" + top +
                '}';
    }
}
